package com.multysite.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.NamespaceManager;
import com.multysite.entity.News;
import com.multysite.entity.Tag;
import com.multysite.entity.admin.ApplicationConfig;
import com.multysite.entity.admin.ApplicationTemplate;
import com.multysite.model.CategoryModel;
import com.multysite.model.TagModel;
import com.multysite.quercus.CompileScriptEngine;
import com.multysite.util.RecentViewHelper;
import com.multysite.util.Setting;

@SuppressWarnings("serial")
public class TagServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(TagServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			System.out.println("Current NS : " + NamespaceManager.get());
			req.setCharacterEncoding("utf-8");
			ApplicationTemplate template = (ApplicationTemplate) req
					.getAttribute("template");
			ApplicationConfig config = (ApplicationConfig) req
					.getAttribute("config");
			if (template != null && config != null) {
				/*
				 * get detail content
				 */
				String[] splitted = req.getRequestURI().split("/");
				if (splitted.length == 3) {
					String tagAlias = splitted[2];
					tagAlias = URLDecoder.decode(tagAlias, "UTF-8");
					Tag obj = TagModel.getById(tagAlias);
					if (obj != null) {
						int limit = 10;
						int page = 1;
						try {
							page = Integer.parseInt((String) req
									.getParameter("page"));
						} catch (Exception e) {
							page = 1;
						}
						CompiledScript compiledscript = CompileScriptEngine
								.getCompileScript(config.getApplicationId(),
										"tag", template.getTag());

						Bindings bind = compiledscript.getEngine().getBindings(
								ScriptContext.ENGINE_SCOPE);
						bind.put("title_for_layout", config.getTitle());
						bind.put("description_for_layout",
								config.getDescription());
						bind.put("keyword_for_layout", config.getKeyword());
						bind.put("css_for_layout", template.getCss());
						bind.put("js_for_layout", template.getJs());

						CategoryModel cateModel = new CategoryModel();
						cateModel.prepareAll();
						TagModel tagModel = new TagModel();
						tagModel.prepareList();

						bind.put("current_tag", obj);
						bind.put("recent_view",
								RecentViewHelper.getRecentView());
						bind.put("list_tag", tagModel.getListResult());
						bind.put("list_category", cateModel.getListResult());

						List<News> listResult = new ArrayList<News>();
						listResult = obj.recoverListNews();
						int start = (page - 1) * limit;
						double dLimit = limit;
						bind.put("total_page",
								(int) Math.ceil(listResult.size() / dLimit));
						try {
							listResult = listResult
									.subList(start, page * limit);
						} catch (Exception e) {
							try {
								listResult = listResult.subList(start,
										listResult.size());
							} catch (Exception e2) {

							}
						}
						bind.put("articles", listResult);
						bind.put("current_page", page);

						try {
							resp.getWriter().print(
									(String) compiledscript.eval());
						} catch (Exception e) {
							e.printStackTrace();
							log.warning(e.toString());
						}
					} else {
						resp.sendRedirect("/");
					}
				} else {
					resp.sendRedirect("/");
				}
			} else {
				NamespaceManager.set(Setting.getGeneralNamespace());
				resp.sendRedirect("http://" + Setting.getDomain());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.warning(e.toString());
			resp.sendRedirect("/");
		}
	}

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("1");
		list.add("2");
		list.add("3");
		list.add("4");
		list.add("5");
		list.add("6");
		list.add("7");
		list.add("8");
		list.add("9");
		list.add("10");
		list.add("11");
		int limit = 10;
		double dLimit = limit;
		System.out.println((int) Math.ceil(list.size() / dLimit));
	}
}
